package com.ymu.beyond.sshDay2.ques.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

public class QuesAction {
	private String name;
	// 得到上传的文件
	private File file;
	// 得到上传的文件名称
	private String fileFileName;
	// 得到上传的文件内容类型
	private String fileContentType;
	// 下载时正常显示中文
	private String downloadName;

	public String requestList() throws Exception {
		return "requestList";
	}

	// 文件上传
	public String upload() throws Exception {
		System.out.println(name);
		System.out.println(file);
		System.out.println(fileFileName);
		System.out.println(fileContentType);
		String uploadUrl = ServletActionContext.getServletContext().getRealPath("/upload");
		FileInputStream inputStream = null;
		FileOutputStream outputStream = null;
		try {
			inputStream = new FileInputStream(file);
			outputStream = new FileOutputStream(uploadUrl + "/" + fileFileName);
			byte[] bytes = new byte[1024 * 4];
			int len = 0;
			while ((len = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "uploadError";
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
			if (outputStream != null) {
				outputStream.close();
			}
		}
		return "uploadSuccess";
	}

	public String download() throws Exception {
		downloadName = URLEncoder.encode(fileFileName, "UTF-8");
		return "download";
	}

	// 文件下载(注意不要忘记"upload"两边的斜杠 坑)
	public InputStream getDownloadFile() throws Exception {
		ServletContext sc = ServletActionContext.getServletContext();
		return sc.getResourceAsStream("/upload/" + fileFileName);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getDownloadName() {
		return downloadName;
	}

	public void setDownloadName(String downloadName) {
		this.downloadName = downloadName;
	}

}
